package com.learn.demo.netty.tcp.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * MyClientHandler
 *
 * @author banjiawei
 * @date 2022/01/15
 */
@Slf4j
public class MyClientHandler extends SimpleChannelInboundHandler<Message> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {
        log.info("=========================================================================");
        String msg = new String(message.getContent(), StandardCharsets.UTF_8);
        log.info("客户端收到消息：[{}]", msg);
        log.info("=========================================================================\r\n");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 5; i++) {
            String msg = "服务端你好，这里是客户端";
            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
            Message message = new Message();
            message.setLength(bytes.length);
            message.setContent(bytes);
            ctx.writeAndFlush(message);
            log.info("客户端：发送消息给服务端，msg：[{}]", msg);
        }
    }
}
